/*
 * bsp_aht20.c
 *
 *  Created on: Jun 3, 2024
 *      Author: wangb
 */

#include "bsp_aht20.h"

// 内部函数声明
static HAL_StatusTypeDef AHT20_ReadStatus(uint8_t *status);
static HAL_StatusTypeDef AHT20_SendCommand(uint8_t *command, uint16_t size);
static HAL_StatusTypeDef AHT20_ReceiveData(uint8_t *data, uint16_t size);


/*
 * @名字：void AHT20_Init(void)
 * @日期：2024-06-03
 * @功能：初始化AHT20
 * @参数：None
 * @返回值：None
 */
void AHT20_Init(void)
{
    uint8_t status;

    HAL_Delay(40); // 上电等待40ms

    if (AHT20_ReadStatus(&status) != HAL_OK) {
        //printf("读取状态字失败\r\n");
        return;
    }

    if ((status & 0x08) == 0x00) { // 判断Bit[3]是否为1
        //printf("AHT20 初始化失败，等待初始化\r\n");
        uint8_t initCmd[3] = {0xBE, 0x33, 0x00};
        if (AHT20_SendCommand(initCmd, 3) != HAL_OK) {
           // printf("发送初始化命令失败\r\n");
            return;
        }
    } else {
        //printf("AHT20 初始化完成\r\n");
    }
}

/*
 * @名字：void AHT20_ReadData(float *Temperature,float *Humidity)
 * @日期：2024-06-03
 * @功能：获取温度,并且打印出来
 * @参数：float *Temperature 温度
 * 		 float *Humidity    湿度
 * @返回值：None
 */
void AHT20_ReadData(float *Temperature, float *Humidity)
{
    uint8_t data[6];
    uint8_t cmd[3] = {0xAC, 0x33, 0x00};

    if (AHT20_SendCommand(cmd, 3) != HAL_OK) {
        //printf("发送命令失败\r\n");
        return;
    }

    HAL_Delay(75);

    if (AHT20_ReceiveData(data, 6) != HAL_OK) {
       // printf("接收数据失败\r\n");
        return;
    }

    if ((data[0] & 0x80) == 0x00) {
        uint32_t humData = ((uint32_t)data[1] << 12) | ((uint32_t)data[2] << 4) | ((uint32_t)data[3] >> 4);
        *Humidity = humData * 100.0f / (1 << 20);

        uint32_t tempData = (((uint32_t)data[3] & 0x0F) << 16) | ((uint32_t)data[4] << 8) | ((uint32_t)data[5]);
        *Temperature = tempData * 200.0f / (1 << 20) - 50.0f;



    } else {
        //printf("数据无效\r\n");
    }
}

// 内部辅助函数实现

static HAL_StatusTypeDef AHT20_ReadStatus(uint8_t *status)
{
    return HAL_I2C_Master_Receive(&hi2c2, AHT20_ADDRESS, status, 1, HAL_MAX_DELAY);
}

static HAL_StatusTypeDef AHT20_SendCommand(uint8_t *command, uint16_t size)
{
    return HAL_I2C_Master_Transmit(&hi2c2, AHT20_ADDRESS, command, size, HAL_MAX_DELAY);
}

static HAL_StatusTypeDef AHT20_ReceiveData(uint8_t *data, uint16_t size)
{
    return HAL_I2C_Master_Receive(&hi2c2, AHT20_ADDRESS, data, size, HAL_MAX_DELAY);
}
